<template>
  <div class="w-100% h-100%" style="position: relative">
    <div id="luckysheet"></div>
    <div v-show="isMaskShow" id="tip">Downloading</div>
  </div>
</template>

<script setup>
import { ref, onMounted,watch } from 'vue'
import { exportExcel } from './export'
import LuckyExcel from 'luckyexcel'


const isMaskShow = ref(false)
const jsonData = ref({})

const props = defineProps({
  excelUrl:String
});
//监听图表数据时候变化，重新渲染图表
watch(() => props.excelUrl, () => {
  selectExcel();
})


const loadExcel = (evt) => {
  const files = evt.target.files
  if (files == null || files.length == 0) {
    return
  }

  let name = files[0].name
  let suffixArr = name.split('.'),
    suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      return
    }
    jsonData.value = exportJson

    window.luckysheet.destroy()

    window.luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      lang: "zh",
      allowUpdate:false,
      allowEdit: false,
      showtoolbar:false,
      showstatisticBar:false,
    })
  })
}
const selectExcel = () => {
  const value = props.excelUrl
  if (value === '') {
    return
  }
  isMaskShow.value = true

  try {
    LuckyExcel.transformExcelToLuckyByUrl(value, "", (exportJson, luckysheetfile) => {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        return
      }
      jsonData.value = exportJson

      isMaskShow.value = false
      window.luckysheet.destroy()

      window.luckysheet.create({
        container: 'luckysheet', //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
        lang: "zh",
        allowUpdate:false,
        allowEdit: false,
        showtoolbar:false,
        showstatisticBar:false
      })
    })
  }catch (e) {
    isMaskShow.value = false;
  }

}
const downloadExcel = (name) => {
  exportExcel(luckysheet.getAllSheets(), name);
}

// !!! create luckysheet after mounted
onMounted(() => {
  luckysheet.create({
    container: 'luckysheet'
  })
})
defineExpose({
  downloadExcel,
  selectExcel,
  loadExcel
})
</script>

<style  scoped>
#luckysheet {
  margin: 0px;
  padding: 0px;
  position: absolute;
  width: 100%;
  left: 0px;
  top: 0px;
  bottom: 0px;

}
:deep(#luckysheet-copy-btn),:deep(#luckysheet_info_detail){
  display: none !important;
}

#tip {
  position: absolute;
  z-index: 1000000;
  left: 0px;
  top: 0px;
  bottom: 0px;
  right: 0px;
  background: rgba(255, 255, 255, 0.8);
  text-align: center;
  font-size: 40px;
  align-items: center;
  justify-content: center;
  display: flex;
}
</style>
